package com.ivsign.lib_idcardidentification;

import android.os.Message;
import android.util.Log;

import java.util.Arrays;

import static android.content.ContentValues.TAG;

/**
 * @description :
 * @autHor :  Jason
 * @date : 2018/8/17 19:25
 */

public class CoreProcesser {

    int ret = 0, len = 0;
    int rxcounter = 0;
    byte[] RxBuffer = new byte[1500];
    int DataCommand = 0;
    int recvcounter = 0;
    int tmplooptimes = 0;
    // 发送服务器的二代证密文包解码明文响应包
    byte[] BTRecv = new byte[1034];
    private static final String LOGTAG = "log";
    byte[] recData = new byte[1500];
    private byte[] recv_buf = new byte[1423];
    private SocketCommunication socketCommunication;
    private MainHandler mHandler;
    int sleep_times = 3;
    private final Monitor5001Thread monitor5001Thread;
    private volatile boolean isExit;

    public boolean isExit() {
        return isExit;
    }

    public void setExit(boolean exit) {
        isExit = exit;
    }

    public CoreProcesser(SocketCommunication socketCommunication) {
        this.socketCommunication = socketCommunication;
        this.mHandler = socketCommunication.getmHandler();
        //开启监听线程
        monitor5001Thread = new Monitor5001Thread();
        monitor5001Thread.start();

    }

    public void handByte(byte[] value) {

        Log.e("-------------", "notify value--" + Util.bytesToHexString(value) + Thread.currentThread().getName());
        {
            // 打开通知后，设备发过来的数据将在这里出现
            Log.e(LOGTAG, "notify value--" + Util.bytesToHexString(value));
            boolean tmp490rxcounter = false;

            Log.e(LOGTAG, "sleep=======OKOKO=====startReadAging");

            if (value != null) {
                try {
                    if (tmp490rxcounter)
                        Log.e(LOGTAG, "ReadingBT...");
                    len = value.length;
                    System.arraycopy(value, 0, RxBuffer, rxcounter, len);
                    recvcounter += len;
                    rxcounter += len;
                    // if (RxBuffer[0] == 0x02 && RxBuffer[rxcounter - 1] == 0x03 || ((RxBuffer[0] == -1) && (RxBuffer[1] == -1) && (RxBuffer[2] == -1) && RxBuffer[rxcounter - 1] == -2) && RxBuffer[rxcounter - 2] == -2) {
                    if (rxcounter >= 8) {
                        ret = IDCheckUtils.Check_head02_end03(rxcounter, RxBuffer);
                        if (ret == 0x9000) {
                            DataCommand = (RxBuffer[3] << 8) + RxBuffer[4];
                            handCommand();
                            clearData();
                        }
                        ret = IDCheckUtils.Check_headTripleAA(rxcounter, RxBuffer);
                        if ((ret == 0x9000) && (rxcounter == 1295)) {
                            DataCommand = (RxBuffer[5] << 8) + RxBuffer[6];
                            handCommand();
                            clearData();
                        }
                        ret = IDCheckUtils.Check_headTripleFFWith6002(rxcounter, RxBuffer);
                        if ((ret == 0x9000)) {
                            if (rxcounter == 516) {
                                DataCommand = (RxBuffer[5] << 8) + RxBuffer[6];
                                handCommand();
                                clearData();
                            }
                        }

                        if (rxcounter == 490) {
                            ret = IDCheckUtils.Check_headTripleFFWith6013(rxcounter, RxBuffer);
                            if (ret == 0x9000) {
                                DataCommand = (RxBuffer[5] << 8) + RxBuffer[6];
                                if (DataCommand == 0x6013) handCommand();
                                clearData();
                            }

                        }
                        ret = IDCheckUtils.Check_headTripleFFWith6113(rxcounter, RxBuffer);
                        if (ret == 0x9000 && rxcounter == 554) {
                            DataCommand = (RxBuffer[5] << 8) + RxBuffer[6];
                            if (DataCommand == 0x6113)
                                handCommand();
                            clearData();
                        }
                        if (tmp490rxcounter) {
                            tmplooptimes++;
                            Log.e(LOGTAG, DataCommand + ":btdata:" + rxcounter + ":" + tmplooptimes);
                        }

                    }

                    if (recvcounter > 1400) clearData();


                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                }

            }

        }
    }

    private void handCommand() {
        final byte[] send = new byte[recvcounter];
        System.arraycopy(RxBuffer, 0, send, 0, recvcounter);
        Log.e(LOGTAG, "btdata===" + Util.bytesToHexString(send));
        Log.e(LOGTAG, recvcounter + "DataCommand===" + DataCommand);
        Log.e(TAG, "run: " + DataCommand);
        Message message = null;
        switch (DataCommand) {


            case 0x5001://20481
                if (!mHandler.isReadingflag()) {
                    mHandler.setReadingflag(true);
                    if (socketCommunication.TcpInit("122.115.41.165", 10228) == 0) {
                        socketCommunication.sendsocketdata5001(send, 0);
                    }

                    message = Message.obtain();
                    message.what = 02;
                    message.obj = new ProgressResult(20, 0x5001);
                    mHandler.sendMessage(message);
                }

                break;

            case 0x5012://5012
                message = Message.obtain();
                message.what = 02;
                message.obj = new ProgressResult(30, 0x5012);
                mHandler.sendMessage(message);
                socketCommunication.sendsocketdata5012(send, 0);
                break;
            case 0x5022:
                socketCommunication.sendsocketdata5022(send, 0);
//								mHandler.sendEmptyMessage(12);
                message = Message.obtain();
                message.what = 02;
                message.obj = new ProgressResult(40, 0x5022);
                mHandler.sendMessage(message);
                break;
            case 0x6002:
                socketCommunication.sendcardtran(send, 516);
//								mHandler.sendEmptyMessage(12);
                socketCommunication.socketRead_60xx(recData);
                message = Message.obtain();
                message.what = 02;
                message.obj = new ProgressResult(50, 0x6002);
                mHandler.sendMessage(message);
                break;
            case 0x6013:
                Log.e(LOGTAG, "0x6013 btdata===" + Util.bytesToHexString(send));
                Log.e(LOGTAG, "rxcounter===" + rxcounter);
//								sendcardtran(send, 1034);
                System.arraycopy(send, 0, BTRecv, 0, recvcounter);//6003文件
//
                message = Message.obtain();
                message.what = 02;
                message.obj = new ProgressResult(60, 0x6013);
                mHandler.sendMessage(message);
                Log.e(LOGTAG, "rxcounter===" + rxcounter);
                break;
            case 0x6113:
                Log.e(LOGTAG, "rxcounter===" + rxcounter + "0x6113 btdata===" + Util.bytesToHexString(send));

                message = Message.obtain();
                message.what = 02;
                message.obj = new ProgressResult(70, 0x6113);
                mHandler.sendMessage(message);
                //组装数据报文 1034
                /**
                 * 数据包二：拆分以前是6013，长度040a现在拆了2个包一个6013，01ea（490），一个6113长度022A（554）
                 序号	名称	字节数	说明
                 1	包头	3	3字节固定值0xff
                 2	包长度	2	长度=包头+长度+…+包尾，固定值1034字节
                 3	6013	2	0x60 0x13
                 4	6013文件	1024	1024字节6013文件内容
                 10+n	校验字节	1	累加和校验，从长度开始累加，至6013文件结束
                 11+n	包尾	2	固定值0xfe,0xfe
                 */
                System.arraycopy(send, 7, BTRecv, 487, 547);//6013File
                System.arraycopy(Util.hexStringToBytes("ffffff040a6013"), 0, BTRecv, 0, 7);
                final byte[] filesend6013 = new byte[1027];    //1034-7
                System.arraycopy(BTRecv, 7, filesend6013, 0, filesend6013.length);
//								sendcardtran(BTRecv, 1034);
//								socketRead_60xx();
                Log.e(LOGTAG, "BTRecv===" + Util.bytesToHexString(BTRecv));
                int ReadnLen = socketCommunication.sendNew6013AndReceive(filesend6013, "6013", 1034, recv_buf);
                if (checkcommbuf(recv_buf, "aaaaaa966905080000900100", 12) == 0) {
                    //  byte[] recv_ID_from_Server = new byte[1295];// 服务返回完整数据包
                    if (ReadnLen != 1295) {
//                                try {
//                                    Tcpsocket.setSoTimeout(200);
//                                    int readlen = TcpSocketIn.read(recv_ID_from_Server);
//                                    if ((readlen + ReadnLen) != 1295) {
////												if(ReadnLen != 1412)
//                                        mHandler.sendEmptyMessage(4);  //重新发送请求
//                                    }
//
//                                    Log.e(LOGTAG, "BTRecv===" + Util.bytesToHexString(recv_ID_from_Server));
//                                    System.arraycopy(recv_ID_from_Server, 0, recv_buf, ReadnLen, 1423 - ReadnLen);
//                                    System.arraycopy(recv_buf, 0, recData, 0, 1295);
//                                    mHandler.obtainMessage(03, 20, -1, null).sendToTarget();
//
//                                } catch (IOException e) {
//                                    // TODO Auto-generated catch block
//                                    mHandler.sendEmptyMessage(4);  //重新发送请求
//                                    e.printStackTrace();
//                                }
                    }
                    System.arraycopy(recv_buf, 0, recData, 0, 1295);
                    mHandler.obtainMessage(03, 20, -1, recData).sendToTarget();
                    message = Message.obtain();
                    message.what = 02;
                    message.obj = new ProgressResult(100, 0x6113);
                    mHandler.sendMessage(message);
                } else {
                    mHandler.obtainMessage(4).sendToTarget();
                    // mHandler.sendEmptyMessageDelayed(44, 3000);
                }
//								mHandler.sendEmptyMessage(12);  //What's it means?
//								pb.setProgress(60);


                break;
            case 0x0508:    //Just for test
//								System.arraycopy(send, 0, recData, 0, 1295);
                mHandler.obtainMessage(03, 20, -1, null).sendToTarget();
                break;
            default:
                break;
        }
    }


    private void clearData() {
        DataCommand = 0;
        recvcounter = 0;
        tmplooptimes = 0;
        rxcounter = 0;
        Arrays.fill(RxBuffer, (byte) 0);
        return;

    }


    private int checkcommbuf(byte[] commin, String constbuf, int len) {
        byte[] bufcompare = new byte[len];

        System.arraycopy(commin, 0, bufcompare, 0, bufcompare.length);
        return Util.bytesToHexString(bufcompare).compareTo(constbuf);
    }

    public void reset() {
        clearData();
        mHandler.setReadingflag(false);
    }

    public void close() {
        if (monitor5001Thread != null) {

            monitor5001Thread.exit();

        }
    }

    class Monitor5001Thread extends Thread {
        public void run() {
            while (!isExit) {

                {
//					startRfidSendingThread(mSearchCardCmd, mSearchCardCmd.length);
                    if ((sleep_times >= 3) && (mHandler.isReadingflag() == false)) {
//					if(!IDNRsock.UartInUsing)){
//						IDNRsock.RxCounter = 0;
                        Log.e(TAG, "run: " + "sdf");
                        clearData();
                        socketCommunication.getIdCardCommunication().sendcardtran5000ByBle();
                        sleep_times = 0;
//						IDNRsock.ReadIDInStep = 0;
                    }
                }

                try {
                    sleep(1000);
                    sleep_times++;
                } catch (InterruptedException e) {
                    Log.e(TAG, "run: " + e.getMessage());
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        public void exit() {
            isExit=true;
        }

        ;
    }

}